package com.stu.covid.config.security;

import com.stu.covid.business.entity.User;
import com.stu.covid.business.mapper.StudentMapper;
import com.stu.covid.business.mapper.TeacherMapper;
import com.stu.covid.business.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;


@Component
@Slf4j
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录判断开始:{}", username);
        //判断用户名是否存在,此处不用比较密码，springsecurity会自动判断
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名没有找到");
        }
        if(user.getRole().equals("teacher")){
            user.setTeacher(teacherMapper.selectByUserId(user.getId()));
        }else if(user.getRole().equals("student")){
            user.setStudent(studentMapper.selectByUserId(user.getId()));
        }
        return user;
    }
}
